﻿using Microsoft.Extensions.Logging;
using Quartz;
using SimulationCenter.Schedulers;
using SimulationCenter.Tasks;
using SimulationCenter.Tasks.Svrs;
using System;
using System.Threading.Tasks;

namespace SimulationCenter.Jobs
{
    public class ScJob : IJob
    {
        public const string ScTaskId = "scTaskId";

        /// <summary>
        /// 关联任务编号
        /// </summary>
        private int _scTaskId;

        private readonly ITaskSvr _taskSvr;
        private readonly ScScheduleManager _scheduleManager;
        private readonly ILogger<ScJob> _logger;

        public ScJob(ITaskSvr taskSvr, ScScheduleManager scheduleManager, ILogger<ScJob> logger)
        {
            _taskSvr = taskSvr;
            _scheduleManager = scheduleManager;
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            var dataMap = context.JobDetail.JobDataMap;
            _scTaskId = dataMap.GetInt(ScTaskId);

            // 检索任务详情
            var scTask = await _taskSvr.GetTask(_scTaskId);

            // 当前不为初始化任务， 检查初始化任务是否执行完成
            if (!TaskSvr.START_UP_TASK.Equals(scTask.Name))
            {
                var startUpTask = await _taskSvr.GetRunningStartUpTask();
                if (startUpTask != null)
                {
                    _logger.LogInformation($"初始化任务并未结束， 本次任务 {scTask.Id}_{scTask.Name} 延迟执行");
                    return;
                }
            }

            // 关联设备
            var targetDevices = scTask.TargetDevices.Split(",");
            if (targetDevices.Length == 0) return;

            scTask.Status = ScTaskStatus.Running;
            scTask.StartAt = DateTime.Now;
            scTask.EndAt = null;
            await _taskSvr.UpdateTask(scTask);

            // 添加子任务调度器
            foreach (var device in targetDevices)
            {
                await _scheduleManager.AddDeviceTaskSchedule(_scTaskId, device);
            }
        }
    }
}
